//
//  ViewController.m
//  GitBucket
//
//  Created by 3024 on 15/11/2.
//  Copyright © 2015年 ios25. All rights reserved.
//

#import "ViewController.h"



@interface ViewController ()
{
    
    UIWebView *_webView;
    
    NSString *code;
    
    NSString *token;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"repos.json"];
    NSLog(@"path:%@",path);
        

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)loginPressed {
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    _webView.delegate = self;
    _webView.hidden = NO;
}

//webview的代理方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest absoluteString:%@",request.URL.absoluteString);
//        //如果准备跳到百度则隐藏webView
        NSString *urlString = [NSString stringWithString:request.URL.absoluteString];
    
        if (urlString != nil) {
            if ([urlString rangeOfString:@"baidu.com"].location != NSNotFound) {
                _webView.alpha = 0;
            }
        }
    
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    //发现网址已跳到百度说明授权成功 获取code 继续请求
    if ([webView.request.URL.absoluteString rangeOfString:@"baidu"].location != NSNotFound) {
        
        //获取code 只获取一次就够了
        if (code ==nil) {
            
            code = [webView.request.URL.absoluteString substringFromIndex:webView.request.URL.absoluteString.length-20];
            NSLog(@"code:%@",code);
            //取得code就移除webView
            [_webView removeFromSuperview];
        }
        //获取token 只获取一次就够了
        if (token == nil) {
            
            NSString *tokenWeb = [NSString stringWithFormat:@"https://github.com/login/oauth/access_token?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa&code=%@",code];
            
            //获取数据转换成字符串
            //            NSString *toketokenFileString =[[NSString alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tokenWeb]] encoding:NSUTF8StringEncoding];
            
            //            NSLog(@"toketokenFileString:%@",toketokenFileString);
            
            token = [[[NSString alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tokenWeb]] encoding:NSUTF8StringEncoding] substringWithRange:NSMakeRange(13, 40)];
            NSLog(@"token:%@",token);
            
            
            //接着直接存为文件以便访问
            //获取json文件
            //            NSString *jsonwebString = [NSString stringWithFormat:@"https://api.github.com/user?access_token=%@",token];
            
            NSString *json = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.github.com/user?access_token=%@",token]]]
                                                  encoding:NSUTF8StringEncoding];
            //            NSLog(@"%@",json);
            
            //存入文件
            //文件路径
            NSString *jsonFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"user.json"];
            NSLog(@"%@",jsonFilePath);
            //把字符串写入文件
            NSError *error = nil;
            if (![json writeToFile:jsonFilePath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
                NSLog(@"写入文件错误:%@",error);
            }else
            {
                NSLog(@"写入文件成功");
                //由于有些需要再次请求
                //所以写入成功立即取出文件
                
                //读成字典
                NSData *jsonData = [[NSData alloc]initWithContentsOfFile:jsonFilePath];
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                
                //请求图片
                NSURL *avatar_url = [NSURL URLWithString:jsonDict[@"avatar_url"]];
                NSData *avatar_data = [NSData dataWithContentsOfURL:avatar_url];
                //图片保存路径
                NSString *avatarFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"avatar_image.data"];
                //保存图片
                if ([avatar_data writeToFile:avatarFilePath atomically:YES]) {
                    NSLog(@"写入avatar成功");
                }
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                
                //请求repos
                NSString *repos_url_str = jsonDict[@"repos_url"];
            
                NSString *repos_url_str_long = [NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",repos_url_str];
                NSURL *repos_url = [NSURL URLWithString:repos_url_str_long];
                NSData *repos_data = [NSData dataWithContentsOfURL:repos_url];
                //repos保存路径
                NSString *reposFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"repos.json"];
                //保存repos.json
                if ([repos_data writeToFile:reposFilePath atomically:YES]) {
                    NSLog(@"写入repos成功");
                }
                
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                
                //请求starred
                //需要修改一下url
                NSString *string = jsonDict[@"starred_url"];
                NSString *starurl = [string substringToIndex:string.length-15];
                NSString *starurl_long = [NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",starurl];
                
                NSURL *starred_url = [NSURL URLWithString:starurl_long];
                NSData *starred_data = [NSData dataWithContentsOfURL:starred_url];
                //repos保存路径
                NSString *starredFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"starred.json"];
                //保存repos.json
                if (![starred_data writeToFile:starredFilePath atomically:YES]) {
                    NSLog(@"写入repos不成功");
                }
                
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                //请求received_events_url
                NSString *received_events_str = jsonDict[@"received_events_url"];
                
                NSString *received_events_str_long = [NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",received_events_str];
                
                NSURL *received_events_url = [NSURL URLWithString:received_events_str_long];
                NSData *received_events_url_data = [NSData dataWithContentsOfURL:received_events_url];
                //保存路径
                NSString *received_events_url_FilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"received_events_url.json"];
                //保存
                if ([received_events_url_data writeToFile:received_events_url_FilePath atomically:YES]) {
                    NSLog(@"写入received_events_url成功");
                    //发送通知通知可以更新视图了
                    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                    
                    [center postNotificationName:@"updateDateSouce" object:self userInfo:nil];
                }
                
            }
            
        }
    }
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSLog(@"webViewDidFinishLoad");
    
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    //如果授权还在，就不用进入授权页面
    if ([[NSData alloc]initWithContentsOfFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"user.json"]] == nil) {
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3D7222dd6497b25737c70c"]]];
        [[segue destinationViewController].view addSubview:_webView];
    }
    
    
}

- (IBAction)usingSafariToLogIn
{
    //提示框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"“GitBucket” wants to open “safari”" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *open = [UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        //跳转到手机自带浏览器
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://github.com/login"]];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }];
    
    [alertController addAction:open];
    [alertController addAction:cancel];
    
    //以模态视图呈现
    [self presentViewController:alertController animated:YES completion:nil];
}


@end
